package com.auto.survey.geocom

import android.bluetooth.BluetoothDevice
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import com.auto.survey.activity.bluetooth.BluetoothService
import com.auto.survey.base.CustomApplication
import com.auto.survey.log.AppLogger
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import com.google.gson.Gson

class GeoComHelper private constructor(val bluetoothmanager: BluetoothManagerUtil) {

    // 单例实现
    companion object {
        @Volatile
        private var instance: GeoComHelper? = null

        fun getInstance(bluetoothmanager: BluetoothManagerUtil): GeoComHelper {
            return instance ?: synchronized(this) {
                    instance ?: GeoComHelper(bluetoothmanager).also {
                    instance = it
                }
            }
        }
    }

    private val resultCallbackList = mutableListOf<((List<GeoCom>, CommandContext) -> Unit)?>()

    private var receiveBtInfoCallback: ((String) -> Unit)? = null

    private var btDiscoverDeviceState:((Boolean) -> Unit)?=null

    private var btConnectionStateChanged:((BluetoothDevice, BluetoothService.ConnectionState) -> Unit)?=null

    private var btError:((String) -> Unit)? = null


    private val geoComExecutor = GeoExecutor().setConditionChecker { previousResult ->
        // 示例条件：前一个命令结果包含"success"
//        previousResult.contains("success", ignoreCase = true)
        val tempTime = System.currentTimeMillis()
        val createTime = Helper.formatTimestamp(tempTime, "yyyy-MM-dd hh:mm:ss")
        val resultAndTime = "###$createTime ### $previousResult"
        AppLogger.getInstance(CustomApplication.getContext()).i("CommandHelper", "命令执行完成:$resultAndTime")

        val tempRlt = previousResult.trim('\r', '\n')
        var pass = true
        if (tempRlt.isBlank() || !tempRlt.startsWith("%R1P")) {
            Log.e("CommandHelper", "数据格式不正确")
            AppLogger.getInstance(CustomApplication.getContext()).e("CommandHelper", "数据格式不正确")
            pass = false
        }

        // 按冒号分割，获取数据部分
        val parts = tempRlt.split(":")
        if (parts.size != 2) {
            Log.e("CommandHelper", "数据格式不正确，缺少冒号分隔符")
            AppLogger.getInstance(CustomApplication.getContext()).e("CommandHelper", "数据格式不正确，缺少冒号分隔符")
            pass = false
        }

        // 按逗号分割数据部分
        val values = parts[1].split(",")
        if (values.isEmpty()) {
            Log.e("CommandHelper", "数据部分缺少必要的字段")
            AppLogger.getInstance(CustomApplication.getContext()).e("CommandHelper", "数据部分缺少必要的字段")
            pass = false
        }

        if (values[0] != "0") {
            Log.e("CommandHelper", "当前响应结果：$previousResult 响应结果失败, 返回的结果RC值不为0， RC=${values[0]}")
            pass = false
        }

        pass

    }.setConditionParse { result ->
        val tempRlt = result.trim('\r', '\n').split(":")[1].split(",")
        Gson().toJson(tempRlt)
    } .setResultExecutorCallback { result, params->
        resultCallbackList.forEach {
            it?.invoke(result, params)
        }
    }




    private val bluetoothCallback = object : BluetoothService.ConnectionCallback{
        override fun onDiscoverDeviceState(isdiscovery: Boolean) {
            btDiscoverDeviceState?.invoke(isdiscovery)
        }

        override fun onConnectionStateChanged(device: BluetoothDevice, state: BluetoothService.ConnectionState) {
            btConnectionStateChanged?.invoke(device, state)
        }

        override fun onDataReceived(device: BluetoothDevice, data: ByteArray) {
            val result = String(data, charset(Charsets.UTF_8.toString()))
            receiveBtInfoCallback?.invoke(result)
        }

        override fun onError(message: String) {
            btError?.invoke(message)
        }
    }


    fun init(){
        Handler(Looper.getMainLooper()).postDelayed(kotlinx.coroutines.Runnable {
            bluetoothmanager.registerCallback(bluetoothCallback)
        }, 1000)
    }

    fun release() {
        bluetoothmanager.unregisterCallback(bluetoothCallback)
    }

    fun startExecution(geocoms:List<GeoCom>) {
        geoComExecutor.startExecution(executGeoGcomList(geocoms), CommandContext())
    }

    fun startExecution(geocoms:List<GeoCom>, params:CommandContext) {
        geoComExecutor.startExecution(executGeoGcomList(geocoms), params)
    }

    private fun executGeoGcomList(geocoms:List<GeoCom>):List<IGeoComExecutor> {
        val list = mutableListOf<IGeoComExecutor>()
        geocoms.forEach {
            val core = GeoComExecutCore(bluetoothmanager, it, this@GeoComHelper)
            list.add(core)
        }
        return list
    }

    // 封装命令执行逻辑
    suspend fun executeCommands(commands: List<GeoComExecutCore>): List<GeoCom> {
        return geoComExecutor.executeCommandsSequentially(commands)
    }


    fun receiveBtInfoCallback(callback: (String) -> Unit) {
        receiveBtInfoCallback = callback
    }

    fun removeReceiveBtnInfoCallback() {
        receiveBtInfoCallback = null
    }

    fun onDiscoverDeviceState(callback:(Boolean) -> Unit){
        this.btDiscoverDeviceState = callback
    }

    fun onConnectionStateChanged(callback:(BluetoothDevice, BluetoothService.ConnectionState) -> Unit){
        this.btConnectionStateChanged = callback
    }

    fun resultCallback(callback: (List<GeoCom>,CommandContext) -> Unit) {
        resultCallbackList.add(callback)
    }

    fun isRegisterCallback(callback: (List<GeoCom>,CommandContext) -> Unit):Boolean {
        return resultCallbackList.contains(callback)
    }

    fun removeResultCallback() {
        resultCallbackList.removeLast()
    }

    fun removeResultCallback(callback: (List<GeoCom>,CommandContext) -> Unit){
        resultCallbackList.remove(callback)
    }

    fun onError(callback: (String) -> Unit){
        this.btError = callback
    }

}